﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;


public partial class Forma_2 : System.Web.UI.Page
{
    private String SessionID;
    private Boolean FolioExists;
    private Int32 Folio;
    private Int32 IdIEP;

    private void Page_Load(object sender, System.EventArgs e)
    {
        SessionValidation();

        // Se verifíca si existe un Folio actual para cargar los datos
        // que han sido previamente guardados
        DatabaseConnection dbCon = new DatabaseConnection();
        FolioExists = dbCon.FolioExistsForCurrentUser(ref Folio, SessionID);
        dbCon.CloseConnection();

        if (FolioExists && !Page.IsPostBack)
        {
            LoadFormWithPastData();
        }
    }

    private void FillTextBoxes()
    {
        foreach (Control c in Form.Controls)
        {
            if (c.Controls.Count > 0)
            {
                foreach (Control c2 in c.Controls)
                {
                    if (c2 is TextBox && (c2.ID.StartsWith("Ingresos") || c2.ID.StartsWith("Egresos")))
                    {
                        ((TextBox)c2).Text = String.Format("{0:F2}", 0);
                    }
                }
            }
        }
    }

    private void LoadFormWithPastData()
    {
        DatabaseConnection dbCon = new DatabaseConnection();
        String concepto, Smonto;

        String queryI = "SELECT *" +
            " FROM [wbecfildb].[dbo].[IngresosPersonal] " +
            " WHERE [IngresosPersonal].[Folio] =  " + Folio + ";";

        SqlDataReader ConceptosReader = dbCon.ExecuteSelect(queryI);

        while (ConceptosReader.Read())
        {
            foreach (Control c in Form.Controls)
            {
                if (c.Controls.Count > 0)
                {
                    foreach (Control c2 in c.Controls)
                    {
                        concepto = ConceptosReader["IngresosPersonal_Concepto"].ToString();
                        if (c2 is TextBox && c2.ID.Equals(concepto))
                        {
                            Smonto = ConceptosReader["IngresosPersonal_Monto"].ToString();
                            ((TextBox)c2).Text = String.Format("{0:F2}", float.Parse(Smonto));
                        }
                    }
                }
            }
        }
        ConceptosReader.Close(); //END INGRESOS

        String queryE = "SELECT *" +
            " FROM [wbecfildb].[dbo].[EgresosPersonal] " +
            " WHERE [EgresosPersonal].[Folio] =  " + Folio + ";";

        ConceptosReader = dbCon.ExecuteSelect(queryE);

        while (ConceptosReader.Read())
        {
            foreach (Control c in Form.Controls)
            {
                if (c.Controls.Count > 0)
                {
                    foreach (Control c2 in c.Controls)
                    {
                        concepto = ConceptosReader["EgresosPersonal_Concepto"].ToString();
                        if (c2 is TextBox && c2.ID.Equals(concepto))
                        {
                            Smonto = ConceptosReader["EgresosPersonal_Monto"].ToString();
                            ((TextBox)c2).Text = String.Format("{0:F2}", float.Parse(Smonto));
                        }
                    }
                }
            }
        }
        ConceptosReader.Close();//END EGRESOS
        dbCon.CloseConnection();
    }


    protected void InsertData(object sender, EventArgs e)
    {
        String query; //insert o update
        Boolean existe;
        DatabaseConnection dbCon = new DatabaseConnection();
        String[] IngresoEgreso = { "IngresosPersonal", "EgresosPersonal" };
        int index;

        foreach (Control c in Form.Controls)
        {
            if (c.Controls.Count > 0)
            {
                foreach (Control c2 in c.Controls)
                {
                    if (c2 is TextBox && (c2.ID.StartsWith("Ingresos") || c2.ID.StartsWith("Egresos")))
                    {
                        if (c2.ID.StartsWith("Ingresos"))
                        {
                            existe = dbCon.ConceptoExistsForCurrentUser(ref IdIEP, Folio, c2.ID, IngresoEgreso[0]);
                            index = 0;
                        }
                        else
                        {
                            existe = dbCon.ConceptoExistsForCurrentUser(ref IdIEP, Folio, c2.ID, IngresoEgreso[1]);
                            index = 1;
                        }

                        if (!existe)
                        {
                            query = "INSERT INTO [wbecfildb].[dbo].[" + IngresoEgreso[index] + "]" +
                                         "([Folio] ,[" + IngresoEgreso[index] + "_Concepto] ,[" + IngresoEgreso[index] + "_Monto])" +
                                         "VALUES (" + Folio + ",'" + (((TextBox)c2).ID) + "','" + (((TextBox)c2).Text) + "')";
                        }
                        else
                        {
                            query = "UPDATE [wbecfildb].[dbo].[" + IngresoEgreso[index] + "] SET " +
                                "[" + IngresoEgreso[index] + "_Concepto] = '" + (((TextBox)c2).ID) + "', " +
                                "[" + IngresoEgreso[index] + "_Monto] = '" + (((TextBox)c2).Text) + "' " +
                                "WHERE [Id" + IngresoEgreso[index][0] + "P] = " + IdIEP + ";";
                        }
                        int rowsAffected = dbCon.ExecuteNonQuery(query);
                    }
                }
            }
        }
        dbCon.CloseConnection();
        Response.Redirect("~/Forma/Forma3.aspx");
    }

    /*
     *  Fija todos los Ingresos y Egresos del alumno a 0.00 en la Base de Datos
     * 
     */
    protected void Borrar(object sender, EventArgs e)
    {
        String query; //insert o update
        Boolean existe;
        DatabaseConnection dbCon = new DatabaseConnection();
        String[] IngresoEgreso = { "IngresosPersonal", "EgresosPersonal" };
        int index;

        foreach (Control c in Form.Controls)
        {
            if (c.Controls.Count > 0)
            {
                foreach (Control c2 in c.Controls)
                {
                    if (c2 is TextBox && (c2.ID.StartsWith("Ingresos") || c2.ID.StartsWith("Egresos")))
                    {
                        if (c2.ID.StartsWith("Ingresos"))
                        {
                            existe = dbCon.ConceptoExistsForCurrentUser(ref IdIEP, Folio, c2.ID, IngresoEgreso[0]);
                            index = 0;
                        }
                        else
                        {
                            existe = dbCon.ConceptoExistsForCurrentUser(ref IdIEP, Folio, c2.ID, IngresoEgreso[1]);
                            index = 1;
                        }

                        if (!existe)
                        {
                            query = "INSERT INTO [wbecfildb].[dbo].[" + IngresoEgreso[index] + "]" +
                                         "([Folio] ,[" + IngresoEgreso[index] + "_Concepto] ,[" + IngresoEgreso[index] + "_Monto])" +
                                         "VALUES (" + Folio + ",'" + (((TextBox)c2).ID) + "','" + 0.00 + "')";
                        }
                        else
                        {
                            query = "UPDATE [wbecfildb].[dbo].[" + IngresoEgreso[index] + "] SET " +
                                "[" + IngresoEgreso[index] + "_Concepto] = '" + (((TextBox)c2).ID) + "', " +
                                "[" + IngresoEgreso[index] + "_Monto] = '" + 0.00 + "' " +
                                "WHERE [Id" + IngresoEgreso[index][0] + "P] = " + IdIEP + ";";
                        }
                        int rowsAffected = dbCon.ExecuteNonQuery(query);
                    }
                }
            }
        }
        dbCon.CloseConnection();
        Response.Redirect("~/Forma/Forma4.aspx");
    }

    /* Valida que la sesión del usuario sea la correcta para mostrar
    * el contenido de esta página
    */
    protected void SessionValidation()
    {
        SessionID = (String)Session["SessionID"];
        String UserType = (String)Session["UserType"];

        if (String.IsNullOrEmpty(SessionID) || String.IsNullOrEmpty(UserType))
        {
            Session.RemoveAll();
            Response.Redirect("~/Default.aspx");
        }
        else
        {
            if (!String.Equals(UserType, "Alumnos"))
            {
                Session.RemoveAll();
                Response.Redirect("~/Default.aspx");
            }
        }
    }
}

